<template>
  <div class="blacklist-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <el-page-header @back="$router.go(-1)">
        <template #content>
          <div class="page-title-section">
            <el-text size="large" tag="h1" class="page-title">设备黑名单管理</el-text>
            <el-text type="info" class="page-description">管理被过滤的设备列表，黑名单中的设备不会在测试执行页面显示</el-text>
          </div>
        </template>
      </el-page-header>
    </div>

    <!-- 操作区域 -->
    <el-card class="action-card" shadow="never">
      <template #header>
        <div class="card-header">
          <el-text size="large" tag="h3">添加设备到黑名单</el-text>
        </div>
      </template>
      
      <el-form :model="formData" :rules="rules" ref="addForm" @submit.prevent="addToBlacklist">
        <el-form-item prop="deviceId">
          <div class="input-group">
            <el-input
              v-model="formData.deviceId"
              placeholder="请输入设备ID"
              clearable
              size="large"
              @keyup.enter="addToBlacklist"
              :disabled="loading"
            >
              <template #prefix>
                <el-icon><Cellphone /></el-icon>
              </template>
            </el-input>
            <el-button 
              type="primary"
              size="large"
              @click="addToBlacklist"
              :loading="loading"
              :disabled="!formData.deviceId.trim()"
            >
              添加到黑名单
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 所有设备列表 -->
    <el-card class="devices-card" shadow="never">
      <template #header>
        <div class="card-header">
          <el-text size="large" tag="h3">所有设备</el-text>
          <el-button 
            @click="fetchAllDevices" 
            :loading="loadingDevices"
            circle
          >
            <el-icon><Refresh /></el-icon>
          </el-button>
        </div>
      </template>
      
      <div v-loading="loadingDevices" element-loading-text="正在加载设备列表...">
        <div v-if="allDevices.length > 0" class="devices-grid">
          <el-card 
            v-for="device in allDevices" 
            :key="device.id" 
            class="device-card"
            :class="{ 'in-blacklist': isInBlacklist(device.id) }"
            shadow="hover"
          >
            <div class="device-info">
              <el-text size="large" tag="div" class="device-name">
                <el-icon><Cellphone /></el-icon>
                {{ device.name }}
              </el-text>
              <el-text type="info" size="small" class="device-description">{{ device.description }}</el-text>
              <el-tag 
                :type="device.status === 'running' ? 'success' : 'info'" 
                size="small"
                class="device-status-tag"
              >
                {{ device.status === 'running' ? '运行中' : '空闲' }}
              </el-tag>
            </div>
            <div class="device-actions">
              <el-button 
                v-if="!isInBlacklist(device.id)"
                type="danger"
                size="small"
                @click="addDeviceToBlacklist(device.id)"
                :loading="loading"
              >
                <el-icon><Close /></el-icon>
                加入黑名单
              </el-button>
              <el-button 
                v-else
                type="success"
                size="small"
                @click="removeFromBlacklist(device.id)"
                :loading="loading"
              >
                <el-icon><Check /></el-icon>
                移出黑名单
              </el-button>
            </div>
          </el-card>
        </div>
        
        <el-empty v-else description="暂无设备数据" />
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Refresh, Close, Check } from '@element-plus/icons-vue';
import { Cellphone } from '@element-plus/icons-vue';
import apiClient from '@/api/auth';

export default {
  name: 'BlacklistManageView',
  components: {
    Cellphone,
    Refresh,
    Close,
    Check
  },
  setup() {
    // 响应式数据
    const loading = ref(false);
    const loadingBlacklist = ref(false);
    const loadingDevices = ref(false);
    
    const blacklistDevices = ref([]); // 设备ID数组，用于快速检查
    const allDevices = ref([]);
    
    const formData = reactive({
      deviceId: ''
    });
    
    const rules = {
      deviceId: [
        { required: true, message: '请输入设备ID', trigger: 'blur' },
        { min: 1, max: 100, message: '设备ID长度应在1到100个字符之间', trigger: 'blur' }
      ]
    };

    // 方法
    const fetchBlacklist = async () => {
      loadingBlacklist.value = true;
      try {
        const response = await apiClient.get('/api/devices/blacklist');
        console.log('黑名单API响应:', response);
        
        // 适配新的API响应格式
        if (response.data?.blacklist_entries) {
          // 新格式：从 blacklist_entries 数组中提取设备ID
          blacklistDevices.value = response.data.blacklist_entries.map(entry => entry.device_id);
        } else if (response.data?.blacklist_devices) {
          // 旧格式：直接使用 blacklist_devices 数组
          blacklistDevices.value = response.data.blacklist_devices;
        } else {
          blacklistDevices.value = [];
        }
        
        console.log(`获取到 ${blacklistDevices.value.length} 个黑名单设备:`, blacklistDevices.value);
      } catch (error) {
        console.error('获取黑名单失败:', error);
        ElMessage.error(error.message || '获取黑名单失败');
      } finally {
        loadingBlacklist.value = false;
      }
    };

    const fetchAllDevices = async () => {
      loadingDevices.value = true;
      try {
        const response = await apiClient.get('/api/devices/info?use_blacklist=false');
        const devicesData = response.data?.devices_info || [];
        allDevices.value = devicesData.map(device => ({
          id: device.device_id,
          name: device.device_id,
          description: device.model ? `型号: ${device.model}` : '未知设备',
          status: device.status === 'not_running' ? 'not_running' : 'running'
        }));
        console.log(`获取到 ${allDevices.value.length} 个设备`);
      } catch (error) {
        console.error('获取设备列表失败:', error);
        ElMessage.error(error.message || '获取设备列表失败');
      } finally {
        loadingDevices.value = false;
      }
    };

    const addToBlacklist = async () => {
      if (!formData.deviceId.trim()) {
        ElMessage.warning('请输入设备ID');
        return;
      }
      
      try {
        await ElMessageBox.confirm(
          `确定要将设备 "${formData.deviceId.trim()}" 加入黑名单吗？加入后该设备将不会在测试执行页面显示。`,
          '确认加入黑名单',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            center: true
          }
        );
        
        loading.value = true;
        try {
          const response = await apiClient.post('/api/devices/blacklist', {
            device_id: formData.deviceId.trim()
          });
          ElMessage.success(response.message || '设备已添加到黑名单');
          formData.deviceId = '';
          
          // 刷新黑名单
          await fetchBlacklist();
        } catch (error) {
          console.error('添加到黑名单失败:', error);
          ElMessage.error(error.message || '添加到黑名单失败');
        } finally {
          loading.value = false;
        }
      } catch (error) {
        // 用户取消操作
        if (error === 'cancel') {
          console.log('用户取消加入黑名单操作');
        }
      }
    };

    const addDeviceToBlacklist = async (deviceId) => {
      try {
        await ElMessageBox.confirm(
          `确定要将设备 "${deviceId}" 加入黑名单吗？加入后该设备将不会在测试执行页面显示。`,
          '确认加入黑名单',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            center: true
          }
        );
        
        loading.value = true;
        try {
          const response = await apiClient.post('/api/devices/blacklist', {
            device_id: deviceId
          });
          ElMessage.success(response.message || '设备已添加到黑名单');
          
          // 刷新黑名单
          await fetchBlacklist();
        } catch (error) {
          console.error('添加到黑名单失败:', error);
          ElMessage.error(error.message || '添加到黑名单失败');
        } finally {
          loading.value = false;
        }
      } catch (error) {
        // 用户取消操作
        if (error === 'cancel') {
          console.log('用户取消加入黑名单操作');
        }
      }
    };

    const removeFromBlacklist = async (deviceId) => {
      try {
        await ElMessageBox.confirm(
          `确定要将设备 "${deviceId}" 从黑名单中移除吗？`,
          '确认移除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            center: true
          }
        );
        
        loading.value = true;
        try {
          console.log('正在移除黑名单设备:', deviceId);
          const url = `/api/devices/blacklist/${encodeURIComponent(deviceId)}`;
          console.log('请求URL:', url);
          
          const response = await apiClient.delete(url);
          console.log('移除黑名单响应:', response);
          
          ElMessage.success(response.message || '设备已从黑名单中移除');
          
          // 刷新黑名单和设备列表
          await fetchBlacklist();
          await fetchAllDevices();
        } catch (error) {
          console.error('从黑名单移除失败:', error);
          console.error('错误详情:', {
            message: error.message,
            response: error.response,
            status: error.response?.status
          });
          ElMessage.error(error.message || '从黑名单移除失败');
        } finally {
          loading.value = false;
        }
      } catch (error) {
        // 用户取消操作
        if (error === 'cancel') {
          console.log('用户取消移除操作');
        }
      }
    };

    const isInBlacklist = (deviceId) => {
      return blacklistDevices.value.includes(deviceId);
    };

    // 生命周期
    onMounted(() => {
      fetchBlacklist();
      fetchAllDevices();
    });

    return {
      // 响应式数据
      loading,
      loadingBlacklist,
      loadingDevices,
      blacklistDevices,
      allDevices,
      formData,
      rules,
      
      // 方法
      fetchBlacklist,
      fetchAllDevices,
      addToBlacklist,
      addDeviceToBlacklist,
      removeFromBlacklist,
      isInBlacklist
    };
  }
};
</script>

<style scoped>
.blacklist-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  background-color: #f8f9fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
}

.page-title-section {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  margin: 0;
}

.page-description {
  margin: 0;
}

.action-card {
  margin-bottom: 24px;
}

.devices-card {
  margin-bottom: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.input-group {
  display: flex;
  gap: 12px;
  align-items: flex-start;
}

.devices-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 16px;
}

.device-card {
  transition: all 0.2s;
  border: 1px solid var(--el-border-color-light);
}

.device-card.in-blacklist {
  border-color: var(--el-color-danger);
  background-color: var(--el-color-danger-light-9);
}

.device-card:hover {
  transform: translateY(-2px);
}

.device-info {
  margin-bottom: 16px;
}

.device-name {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  margin-bottom: 8px;
}

.device-description {
  margin-bottom: 8px;
}

.device-status-tag {
  margin-top: 4px;
}

.device-actions {
  display: flex;
  justify-content: flex-end;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .blacklist-container {
    padding: 12px;
  }
  
  .devices-grid {
    grid-template-columns: 1fr;
  }
  
  .input-group {
    flex-direction: column;
    align-items: stretch;
  }
  
  .card-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
}

/* Element Plus 组件样式覆盖 */
:deep(.el-page-header__content) {
  margin-left: 0;
}

:deep(.el-card__header) {
  padding: 16px 20px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 0;
}

:deep(.el-empty) {
  padding: 40px 20px;
}
</style> 